<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload, User, Loading, Delete, Picture } from '@element-plus/icons-vue'
import { findEmployee, updateEmployee, uploadImage } from '@/api/school'
import { useUserInfoStore } from "@/stores/userInfo"

const userInfoStore = useUserInfoStore()

const form = ref({
    id: null,
    account: '',
    name: '',
    phone: '',
    email: '',
    gender: null,
    avatar: ''
})

const loading = ref(false)
const editMode = ref(false)
const uploadLoading = ref(false)

const genderOptions = [
    { value: 1, label: '男' },
    { value: 2, label: '女' }
]

const loadEmployeeInfo = () => {
    loading.value = true
    // 从userInfo store中获取当前登录员工的ID
    const currentUserId = userInfoStore.userInfo.id
    if (!currentUserId) {
        ElMessage.error('无法获取当前用户信息')
        loading.value = false
        return
    }
    
    findEmployee(currentUserId).then(res => {
        if (res.data) {
            form.value = { ...res.data }
        }
    }).catch(() => {
        ElMessage.error('获取个人信息失败')
    }).finally(() => {
        loading.value = false
    })
}

const handleEdit = () => {
    editMode.value = true
}

const handleSave = () => {
    if (!form.value.name) {
        ElMessage.error('请输入姓名')
        return
    }
    if (!form.value.phone) {
        ElMessage.error('请输入手机号')
        return
    }
    if (!form.value.email) {
        ElMessage.error('请输入邮箱')
        return
    }
    if (!form.value.gender) {
        ElMessage.error('请选择性别')
        return
    }

    loading.value = true
    updateEmployee(form.value).then(res => {
        ElMessage.success('更新成功')
        editMode.value = false
        // 更新本地存储的用户信息
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        userInfo.name = form.value.name
        userInfo.avatar = form.value.avatar
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        // 更新store中的用户信息
        userInfoStore.setUserInfo(userInfo)
    }).catch(() => {
        ElMessage.error('更新失败')
    }).finally(() => {
        loading.value = false
    })
}

const handleCancel = () => {
    editMode.value = false
    loadEmployeeInfo()
}

const handleAvatarUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }

    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }

    uploadLoading.value = true
    uploadImage(file).then(res => {
        form.value.avatar = res.data
        ElMessage.success('头像上传成功')
    }).catch(() => {
        ElMessage.error('头像上传失败')
    }).finally(() => {
        uploadLoading.value = false
    })

    return false // 阻止自动上传
}

const handleImageError = () => {
    console.warn('头像图片加载失败:', form.value.avatar)
    ElMessage.warning('头像图片加载失败，请重新上传')
    // 可以选择清空无效的头像URL
    // form.value.avatar = ''
}

onMounted(() => {
    loadEmployeeInfo()
})
</script>

<template>
    <div class="employee-info">
        <!-- 页面标题 -->
        <div class="page-header">
            <div class="header-content">
                <h2>个人基本信息</h2>
                <p class="header-desc">查看和编辑您的个人资料</p>
            </div>
        </div>

        <el-card class="info-card" shadow="hover">
            <template #header>
                <div class="card-header">
                    <span class="card-title">基本资料</span>
                    <div class="header-actions">
                        <div v-if="!editMode">
                            <el-button type="primary" :icon="User" @click="handleEdit">编辑资料</el-button>
                        </div>
                        <div v-else class="edit-actions">
                            <el-button type="success" @click="handleSave" :loading="loading">保存</el-button>
                            <el-button @click="handleCancel">取消</el-button>
                        </div>
                    </div>
                </div>
            </template>

            <div class="form-container">
                <el-form :model="form" label-width="120px" :disabled="!editMode" class="employee-form">
                    <el-row :gutter="40">
                        <el-col :span="12">
                            <el-form-item label="员工账号">
                                <el-input v-model="form.account" disabled class="readonly-input">
                                    <template #prefix>
                                        <el-icon><User /></el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>

                            <el-form-item label="员工姓名" required>
                                <el-input 
                                    v-model="form.name" 
                                    placeholder="请输入姓名"
                                    :class="{ 'edit-input': editMode }"
                                >
                                    <template #prefix>
                                        <el-icon><User /></el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>

                            <el-form-item label="手机号码" required>
                                <el-input 
                                    v-model="form.phone" 
                                    placeholder="请输入手机号"
                                    :class="{ 'edit-input': editMode }"
                                >
                                    <template #prefix>
                                        <el-icon>📱</el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>

                            <el-form-item label="电子邮箱" required>
                                <el-input 
                                    v-model="form.email" 
                                    placeholder="请输入邮箱"
                                    :class="{ 'edit-input': editMode }"
                                >
                                    <template #prefix>
                                        <el-icon>✉️</el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>

                            <el-form-item label="性别" required>
                                <el-select 
                                    v-model="form.gender" 
                                    placeholder="请选择性别" 
                                    style="width: 100%;"
                                    :class="{ 'edit-input': editMode }"
                                >
                                    <el-option 
                                        v-for="option in genderOptions" 
                                        :key="option.value" 
                                        :label="option.label"
                                        :value="option.value" 
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="头像">
                                <div class="avatar-section">
                                    <div class="avatar-container">
                                        <el-upload 
                                            :show-file-list="false" 
                                            :before-upload="handleAvatarUpload"
                                            :disabled="!editMode || uploadLoading" 
                                            accept="image/*" 
                                            class="avatar-upload"
                                        >
                                            <div class="avatar-display" :class="{ 'editable': editMode, 'uploading': uploadLoading }">
                                                <div v-if="form.avatar" class="avatar-image">
                                                    <el-image 
                                                        :src="form.avatar" 
                                                        fit="cover" 
                                                        :preview-src-list="[form.avatar]"
                                                        @error="handleImageError"
                                                    >
                                                        <template #error>
                                                            <div class="image-error">
                                                                <el-icon class="error-icon">
                                                                    <Picture />
                                                                </el-icon>
                                                                <span class="error-text">加载失败</span>
                                                            </div>
                                                        </template>
                                                    </el-image>
                                                    <div v-if="editMode" class="avatar-overlay">
                                                        <el-icon class="upload-icon">
                                                            <Upload />
                                                        </el-icon>
                                                        <span class="upload-text">点击更换</span>
                                                    </div>
                                                </div>
                                                <div v-else class="avatar-placeholder">
                                                    <el-icon class="placeholder-icon">
                                                        <User />
                                                    </el-icon>
                                                    <span class="placeholder-text">暂无头像</span>
                                                    <div v-if="editMode" class="upload-hint">点击上传</div>
                                                </div>
                                                <div v-if="uploadLoading" class="upload-loading">
                                                    <el-icon class="loading-icon">
                                                        <Loading />
                                                    </el-icon>
                                                    <span>上传中...</span>
                                                </div>
                                            </div>
                                        </el-upload>
                                        <div v-if="form.avatar && editMode" class="avatar-actions">
                                            <el-button type="danger" size="small" circle @click="form.avatar = ''" title="删除头像">
                                                <el-icon>
                                                    <Delete />
                                                </el-icon>
                                            </el-button>
                                        </div>
                                    </div>
                                    <div v-if="editMode" class="upload-tips">
                                        <p>支持 JPG、PNG、JPEG、GIF 格式</p>
                                        <p>文件大小不超过 2MB</p>
                                        <p>建议尺寸：200x200 像素</p>
                                    </div>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </el-card>
    </div>
</template>

<style scoped>
.employee-info {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 60px);
}

.page-header {
    margin-bottom: 20px;
    padding: 20px 0;
    border-bottom: 2px solid #e4e7ed;
}

.header-content h2 {
    margin: 0 0 8px 0;
    font-size: 28px;
    font-weight: 700;
    color: #303133;
    background: linear-gradient(135deg, #409eff, #67c23a);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.header-desc {
    margin: 0;
    font-size: 14px;
    color: #909399;
    font-weight: 400;
}

.info-card {
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: none;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
}

.header-actions {
    display: flex;
    gap: 12px;
}

.edit-actions {
    display: flex;
    gap: 12px;
}

.form-container {
    padding: 20px 0;
}

.employee-form {
    max-width: 100%;
}

.readonly-input :deep(.el-input__inner) {
    background-color: #f5f7fa;
    color: #909399;
}

.edit-input :deep(.el-input__inner),
.edit-input :deep(.el-select__wrapper) {
    border-color: #409eff;
    box-shadow: 0 0 0 1px #409eff inset;
}

.avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 20px;
}

.avatar-container {
    display: flex;
    align-items: flex-start;
    gap: 16px;
}

.avatar-upload {
    display: inline-block;
}

.avatar-display {
    width: 150px;
    height: 150px;
    border: 3px dashed #dcdfe6;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s ease;
    background: linear-gradient(135deg, #f8f9fa, #ffffff);
}

.avatar-display.editable:hover {
    border-color: #409eff;
    background: linear-gradient(135deg, #f0f9ff, #e6f7ff);
    transform: scale(1.02);
}

.avatar-display.uploading {
    border-color: #409eff;
    background: linear-gradient(135deg, #f0f9ff, #e6f7ff);
}

.avatar-image {
    width: 100%;
    height: 100%;
    position: relative;
}

.avatar-image .el-image {
    width: 100%;
    height: 100%;
    border-radius: 50%;
}

.avatar-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.6);
    color: white;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    border-radius: 50%;
}

.avatar-display.editable:hover .avatar-overlay {
    opacity: 1;
}

.upload-icon {
    font-size: 28px;
    margin-bottom: 8px;
}

.upload-text {
    font-size: 14px;
    font-weight: 500;
}

.avatar-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #909399;
    text-align: center;
}

.placeholder-icon {
    font-size: 60px;
    margin-bottom: 12px;
    color: #c0c4cc;
}

.placeholder-text {
    font-size: 16px;
    margin-bottom: 8px;
    font-weight: 500;
}

.upload-hint {
    font-size: 14px;
    color: #409eff;
    font-weight: 500;
}

.upload-loading {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.95);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #409eff;
    border-radius: 50%;
}

.loading-icon {
    font-size: 28px;
    margin-bottom: 8px;
    animation: rotate 1s linear infinite;
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

.avatar-actions {
    display: flex;
    align-items: flex-start;
    padding-top: 12px;
}

.upload-tips {
    text-align: center;
    color: #909399;
    font-size: 13px;
    line-height: 1.5;
}

.upload-tips p {
    margin: 4px 0;
}

.image-error {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #f56c6c;
    background-color: #fef0f0;
    border-radius: 50%;
}

.error-icon {
    font-size: 40px;
    margin-bottom: 8px;
}

.error-text {
    font-size: 14px;
    font-weight: 500;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
    .employee-info {
        padding: 15px;
    }
    
    .form-container {
        padding: 15px 0;
    }
    
    .avatar-display {
        width: 120px;
        height: 120px;
    }
    
    .placeholder-icon {
        font-size: 48px;
    }
    
    .upload-icon {
        font-size: 24px;
    }
    
    .header-content h2 {
        font-size: 24px;
    }
}
</style>
